<template>
  <div class="register-page">
    <!-- 添加顶部导航栏 -->
    <div class="nav-header">
      <img src="../assets/icons/back.svg" class="back-icon" @click="goBack" />
      <span class="nav-title">注册</span>
    </div>

    <div class="register-container">
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label>用户名</label>
          <input 
            type="text" 
            v-model="username" 
            placeholder="请输入3位以上的用户名" 
            required 
            autocomplete="off" 
          />
        </div>
        <div class="form-group">
          <label>邮箱</label>
          <input 
            type="text" 
            v-model="email" 
            placeholder="请输入校园邮箱" 
            required 
            autocomplete="off" 
          />
        </div>
        <div class="form-group">
          <label>密码</label>
          <div class="password-wrapper">
            <input 
              :type="showPassword ? 'text' : 'password'" 
              v-model="password" 
              placeholder="必须包含大小写字母和数字" 
              required 
              autocomplete="new-password" 
            />
            <svg 
              @click="togglePasswordVisibility" 
              class="toggle-password" 
              xmlns="http://www.w3.org/2000/svg" 
              fill="none" 
              viewBox="0 0 24 24" 
              stroke="currentColor"
            >
              <path 
                v-if="showPassword" 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M13.875 18.825A10.05 10.05 0 0112 19c-5.523 0-10-4.477-10-10S6.477 0 12 0s10 4.477 10 10c0 1.875-.525 3.625-1.425 5.125M15 15l5 5"
              />
              <path 
                v-else 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M15 15l5 5M19 19l-5-5m0 0a7.5 7.5 0 01-10.607-10.607M4.393 4.393A7.5 7.5 0 0115 15z"
              />
            </svg>
          </div>
        </div>
        <div class="form-group">
          <label>确认密码</label>
          <div class="password-wrapper">
            <input 
              :type="showConfirmPassword ? 'text' : 'password'" 
              v-model="confirmPassword" 
              placeholder="请再次输入密码" 
              required 
              autocomplete="new-password" 
            />
            <svg 
              @click="toggleConfirmPasswordVisibility" 
              class="toggle-password" 
              xmlns="http://www.w3.org/2000/svg" 
              fill="none" 
              viewBox="0 0 24 24" 
              stroke="currentColor"
            >
              <path 
                v-if="showConfirmPassword" 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M13.875 18.825A10.05 10.05 0 0112 19c-5.523 0-10-4.477-10-10S6.477 0 12 0s10 4.477 10 10c0 1.875-.525 3.625-1.425 5.125M15 15l5 5"
              />
              <path 
                v-else 
                stroke-linecap="round" 
                stroke-linejoin="round" 
                stroke-width="2" 
                d="M15 15l5 5M19 19l-5-5m0 0a7.5 7.5 0 01-10.607-10.607M4.393 4.393A7.5 7.5 0 0115 15z"
              />
            </svg>
          </div>
        </div>
        <div v-if="errorMessage" style="color:red;">
          {{ errorMessage }}
        </div>
        <button type="submit">注册</button>
      </form>
      
      <div class="login-link">
        <p>
          已有账号？
          <router-link to="/login">立即登录</router-link>
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue' // 添加 computed
import { useRouter } from 'vue-router'
import SideMenu from './SideMenu.vue'

const router = useRouter()
const username = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')

const showPassword = ref(false)
const showConfirmPassword = ref(false)

const errorMessage = ref('')
const isFormValid = computed(() => {
  return username.value.length >= 3 && password.value.length >= 6
})

const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value
}

const handleRegister = async () => {
  errorMessage.value = ''
  
  if (!isFormValid.value) {
    errorMessage.value = '用户名至少3个字符，密码至少6个字符'
    return
  }

  if (password.value !== confirmPassword.value) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  // 额外的密码校验
  const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{6,}$/
  if (!passwordRegex.test(password.value)) {
    errorMessage.value = '密码必须包含大小写字母、数字，长度至少6位'
    return
  }

  try {
    const response = await fetch('api/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        sid: username.value.trim(),  // 去除空格
        password: password.value,
        email: email.value.trim(),  // 添加可选字段
      })
    })

    const data = await response.json()

    if (!response.ok) {
      if (response.status === 400) {
        throw new Error(data.message || '注册参数错误')
      } else if (response.status === 409) {
        throw new Error('用户名已存在')
      }
      throw new Error(data.message || '注册失败')
    }

    // 注册成功
    console.log('注册成功:', data)
    
    // 如果后端返回了token和用户信息就存储
    if (data.token) {
      localStorage.setItem('token', data.token)
      if (data.expires_in) {
        const expiresAt = new Date().getTime() + data.expires_in * 1000
        localStorage.setItem('tokenExpires', expiresAt.toString())
      }
    }
    
    if (data.user) {
      localStorage.setItem('user', JSON.stringify(data.user))
    }
    
    router.push('/login')  // 注册成功后跳转到登录页
  } catch (error) {
    console.error('注册错误:', error)
    errorMessage.value = error.message || '注册失败，请稍后重试'
  }
}

onMounted(() => {
  username.value = ''
  password.value = ''
  confirmPassword.value = ''
})

// 修改返回功能
const goBack = () => {
  router.push('/') // 直接返回主页
}
</script>

<style scoped>
.register-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #ffffff;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.nav-header {
  height: 61px;
  background: #ffffff;
  display: flex;
  align-items: center;
  padding: 0 10px;
  position: relative;
  z-index: 1;
}

.back-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-left: 5px;
  position: absolute;
  left: 10px;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 22px;
  font-weight: 500;
  color: #333333;
  font-family: "SourceHanFontBold";
}

.register-container {
  padding: 30px 25px;
  max-width: 400px;
  margin: 0 auto;
  background: #ffffff;
  color: #333;
  position: relative;
  height: calc(100vh - 61px);
}

.form-group {
  margin-bottom: 20px;
  width: 340px;
  margin-left: auto;
  margin-right: auto;
}

input {
  width: 340px;
  height: 50px;
  padding: 0 12px;
  border: 1px solid #5b5b5b;
  border-radius: 8px;
  background-color: white;
  color: #333;
  margin-bottom: 10px;
  transition: border-color 0.2s;
  box-sizing: border-box;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
  text-align: left;
  padding-left: 0;
}

button {
  width: 340px;
  height: 50px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 40px;
  margin-bottom: 20px;
  display: block;
  background: #9dbce3;
  color: white;
  border: none;
  border-radius: 15px;
  cursor: pointer;
  font-size: 20px;
  transition: transform 0.2s ease-in-out;
}

button:hover {
  background: #8badd4; /* 稍微深一点的hover状态 */
  transform: scale(1.02);
}

.login-link {
  position: static;
  text-align: center;
  color: #5b5b5b;
  width: 100%;
  margin-top: 20px;
}

.login-link p {
  margin: 0;
  padding: 15px 0;
  font-size: 14px;
  line-height: 1.5;
  color: #5b5b5b;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 5px;
}

.login-link a {
  color: #3b82f6;
  text-decoration: none;
  margin-left: 5px;
}

.password-wrapper {
  position: relative;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  cursor: pointer;
  color: #3b82f6;
  stroke: black;
}

input[type="password"]::-ms-reveal,
input[type="password"]::-ms-clear,
input[type="password"]::-webkit-credentials-auto-fill-button {
  display: none !important;
}

/* 禁用自动填充的背景色 */
input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
  -webkit-box-shadow: 0 0 0 30px white inset !important;
  -webkit-text-fill-color: #000 !important;
  transition: background-color 5000s ease-in-out 0s;
}
</style>